package com.txc.realms;


import com.txc.pojo.Root;
import com.txc.pojo.User;
import com.txc.service.RootServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class RootRealms extends AuthorizingRealm {

    @Autowired
    private RootServiceImpl rootService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        Root currentRoot = (Root) subject.getPrincipal();
        if ((currentRoot.getPerms()).equals("Root")) {
//            设置当前用户权限
            info.addStringPermission("Root");
            return info;
        } else {
            info.addStringPermission("noRoot");
            return info;
        }
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
//        从数据库中拿数据比对账号密码
        Root root = rootService.queryRootByName(usernamePasswordToken.getUsername());
        if (root == null) {
            return null; //unknownAccountExcption
        } else if (root != null) {
            if (rootService.queryPwdByName(String.valueOf(usernamePasswordToken.getUsername())) != null) {
                Subject subject = SecurityUtils.getSubject();
                Session session = subject.getSession();
                session.setAttribute("Root", root);
            }
        }
        //第一个参数可以将当前登陆对象丢到授权
        return new SimpleAuthenticationInfo(root, root.getPwd(), "");
    }
}